#include "perosnalchatroom.h"
#include "ui_perosnalchatroom.h"
#include<QNetworkDatagram>
#include<QByteArray>
#include<QJsonArray>
#include<QJsonObject>
#include<QTime>
#include<QJsonDocument>
perosnalchatroom::perosnalchatroom(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::perosnalchatroom)
{

    ui->setupUi(this);
    this->setWindowTitle("chatroom");
    this->setWindowIcon(QPixmap(":/res/wf_Bs.png"));

}



QVector<int> perosnalchatroom::converttime(QString time)
{
    QVector<int>ans;
    time.trimmed();
    int py=time.indexOf("-");
    int year=time.sliced(0,py).toInt();
    py++;
    int pm=time.indexOf("-",py);
    int month=time.sliced(py,pm-py).toInt();
    pm++;
    int pd=time.indexOf(" ",pm);
    int day=time.sliced(pm,pd-pm).toInt();
    QStringList strlist=time.sliced(pd+1).split(":",Qt::SkipEmptyParts);
    int hour=strlist.at(0).toInt();
    int minute=strlist.at(1).toInt();
    int second=strlist.at(2).toInt();
    ans.push_back(year);
    ans.push_back(month);
    ans.push_back(day);
    ans.push_back(hour);
    ans.push_back(minute);
    ans.push_back(second);
    return ans;
}

bool perosnalchatroom::comparetime(QVector<int> r1, QVector<int> r2)
{
    for(int i=0;i<r1.size();i++)
    {
        if(r1[i]!=r2[i])
        {
            if(r1[i]>r2[i])
                return false;
            else
                return true;
        }
    }

}

perosnalchatroom::~perosnalchatroom()
{
    delete ui;
}

void perosnalchatroom::initudpsocket()
{
    uso=new QUdpSocket(this);
    uso->bind(QHostAddress::Any,pri->udpsocket);
    connect(uso,&QUdpSocket::readyRead,this,[=](){
        QNetworkDatagram na=uso->receiveDatagram();
        QByteArray ba=na.data();
        QJsonDocument jd=QJsonDocument::fromJson(ba);
        QJsonObject jo=jd.object();
        QString name=jo.value("name").toString();
        QString content_type=jo.value("content_type").toString();
        QString time=jo.value("time").toString();
        QString content=jo.value("content").toString();
        QString image=jo.value("image").toString();
        qDebug()<<name<<" "<<content;
        othersendmes* osm=new othersendmes;
        osm->init(image,content,time,content_type);
        //更新到消息列表中
        os[name].push_back(osm);
        //更新发送方的最后一条消息
        frienditem* fri=friendlistbyname[name];
        fri->renewnearestmes(content_type,content);
        if(curfriend->name!=name)
            return;
        //考虑当前聊天对象是发送方的情况
        ui->listWidget->addItem(time);
        othersendmes* osi=new othersendmes;
        osi->init(image,content,time,content_type);
        QListWidgetItem* li=new QListWidgetItem(ui->listWidget);
        if(content_type=="text")
        {
            int wordrow=(osi->content.size()-52)/26;
            QListWidgetItem* li=new QListWidgetItem(ui->listWidget);
            li->setSizeHint(QSize(358,70+wordrow*25));
            ui->listWidget->setItemWidget(li,osi);
        }
        ui->listWidget->scrollToBottom();
    });
}

void perosnalchatroom::addonefriend(frienditem *fri)
{
    friendlist[nextpos++]=fri;
    friendlistbyname[fri->name]=fri;
    frienditem* fri_dup=new frienditem;
    fri_dup->init(fri->name,fri->image,"",fri->friendudpsocket);
    QListWidgetItem* li=new QListWidgetItem(ui->friendlist);
    li->setSizeHint(QSize(ui->friendlist->width(),75));
    ui->friendlist->setItemWidget(li, fri_dup);

}

void perosnalchatroom::deleteonefriend(QString name)
{
    frienditem*fri=friendlistbyname[name];
    int pos;
    for(auto&key:friendlist.keys())
    {
        if(friendlist[key]==fri)
        {
            pos=key;
            break;
        }
    }
    friendlistbyname.remove(fri->name);
    nextpos--;
    for(int i=pos;i<nextpos;i++)
    {
        friendlist[i]=friendlist[i+1];
    }
    friendlist.remove(nextpos);
    ui->friendlist->takeItem(pos);
}


void perosnalchatroom::initprivateinfo(privateinfo *pri)
{
    this->pri=pri;
}

void perosnalchatroom::loadfriends(QHash<QString, frienditem *> friends)
{
    this->friendlistbyname=friends;
    for(auto&key:friends.keys())
    {
        frienditem* fri=friends[key];
        QListWidgetItem* li=new QListWidgetItem(ui->friendlist);
        li->setSizeHint(QSize(ui->friendlist->width(),75));
        ui->friendlist->setItemWidget(li, fri);
        friendlist[nextpos++]=fri;
        //默认指向选取第一个联系人
        if(curfriend==nullptr)
        {
            curfriend=fri;
        }
    }
}

void perosnalchatroom::loadfriendmes(QHash<QString,QVector<mysendmes*>> ms,QHash<QString,QVector<othersendmes*>> os)
{
    this->ms=ms;
    this->os=os;
}

void perosnalchatroom::on_textEdit_textChanged()
{
    if(!ui->textEdit->toPlainText().isEmpty())
    {
        ui->sendbtn->setStyleSheet("background-color:#1389bf");
        int wordnum=ui->textEdit->toPlainText().size();
        QString worddisplay=QString::number(wordnum)+"/"+"500";
        ui->wordnum->setText(worddisplay);
    }
    else
    {
        ui->sendbtn->setStyleSheet("background-color:white");
    }
}


void perosnalchatroom::on_sendbtn_clicked()
{
    if(!ui->textEdit->toPlainText().isEmpty())
    {
        //发送消息
        QString mes=ui->textEdit->toPlainText();
        ui->textEdit->clear();
        //更新聊天对象的最后一条消息及ui
        if(curfriend==nullptr)
        {
            qDebug()<<"curfriend is nullptr";
            return;
        }
        curfriend->renewnearestmes("text",mes);
        //更新聊天消息框ui界面
        mysendmes* mymes=new mysendmes(ui->listWidget);
        mymes->init(pri->image,mes,"");
        int wordrow=(mes.size()-52)/26;
        QDate curdate=QDate::currentDate();
        QString time=QString("%1-%2-%3 %4").arg(curdate.year()).arg(curdate.month()).arg(curdate.day()).arg(QTime::currentTime().toString());
        ui->listWidget->addItem(time);
        QListWidgetItem* li=new QListWidgetItem(ui->listWidget);
        li->setSizeHint(QSize(370,70+wordrow*25));
        ui->listWidget->setItemWidget(li,mymes);
        // //发送信号让数据存储到数据库的消息表中去
        if(curfriend==nullptr)
        {
            qDebug()<<"personalchatroom162: curfriend is nullptr";
            return;
        }
        emit addonefriendmes(curfriend->name,"text",mes);
        //通过udpsocket发送到对端
        int friendudpsocket=curfriend->friendudpsocket;
        QJsonObject jo;
        jo.insert("content",mes);
        jo.insert("content_type","text");
        jo.insert("name",pri->name);
        jo.insert("time",time);
        jo.insert("image",pri->image);
        QJsonDocument jd(jo);
        QByteArray ba=jd.toJson();
        if(uso==nullptr)
        {
            qDebug()<<"personalchatroom172: uso is nullptr";
            return;
        }
        uso->writeDatagram(QNetworkDatagram(ba,QHostAddress::Broadcast,friendudpsocket));
        ui->listWidget->scrollToBottom();
    }
}


void perosnalchatroom::on_friendlist_currentRowChanged(int currentRow)
{
    if(friendlist.find(currentRow)==friendlist.end())
        return;
    ui->peoplename->setText(friendlist[currentRow]->name);
    ui->listWidget->clear();
    frienditem* fri=friendlist[currentRow];
    //更新当前聊天对象
    curfriend=fri;
    QString name=fri->name;
    QVector<mysendmes*>retm;
    QVector<othersendmes*>reto;
    if(ms.find(name)!=ms.end())
        retm=ms[name];
    if(os.find(name)!=os.end())
        reto=os[name];
    int sizem=retm.size(),sizeo=reto.size();
    int im=0,io=0;
    while(im<sizem&&io<sizeo)
    {
        QVector<int>rm=converttime(retm[im]->time);
        QVector<int>ro=converttime(reto[io]->time);
        if(comparetime(rm,ro))
        {
            mysendmes* ms=new mysendmes;
            mysendmes* mrs=retm[im];
            ms->init(mrs->image,mrs->content,mrs->time,mrs->content_type);
            ms->setimage(pri->image);
            QString curdate=ms->time;
            ui->listWidget->addItem(curdate);
            if(ms->content_type=="text")
            {
                int wordrow=(ms->content.size()-52)/26;
                QListWidgetItem* li=new QListWidgetItem(ui->listWidget);
                li->setSizeHint(QSize(358,70+wordrow*25));
                ui->listWidget->setItemWidget(li,ms);
            }
            im++;
        }
        else
        {
            othersendmes* os=new othersendmes;
            othersendmes* ors=reto[io];
            os->init(ors->image,ors->content,ors->time,ors->content_type);
            os->setimage(friendlist[currentRow]->image);
            QString curdate=os->time;
            ui->listWidget->addItem(curdate);
            if(os->content_type=="text")
            {
                int wordrow=(os->content.size()-52)/26;
                QListWidgetItem* li=new QListWidgetItem(ui->listWidget);
                li->setSizeHint(QSize(358,70+wordrow*25));
                ui->listWidget->setItemWidget(li,os);
            }
            io++;
        }
    }
    while(im<sizem)
    {
        QVector<int>rm=converttime(retm[im]->time);
        mysendmes* ms=new mysendmes;
        mysendmes* mrs=retm[im];
        ms->init(mrs->image,mrs->content,mrs->time,mrs->content_type);
        ms->setimage(pri->image);
        QString curdate=ms->time;
        ui->listWidget->addItem(curdate);
        if(ms->content_type=="text")
        {
            int wordrow=(ms->content.size()-52)/26;
            QListWidgetItem* li=new QListWidgetItem(ui->listWidget);
            li->setSizeHint(QSize(358,70+wordrow*25));
            ui->listWidget->setItemWidget(li,ms);
        }
        im++;
    }
    while(io<sizeo)
    {
        othersendmes* os=new othersendmes;
        othersendmes* ors=reto[io];
        os->init(ors->image,ors->content,ors->time,ors->content_type);
        os->setimage(friendlist[currentRow]->image);
        QString curdate=os->time;
        ui->listWidget->addItem(curdate);
        if(os->content_type=="text")
        {
            int wordrow=(os->content.size()-52)/26;
            QListWidgetItem* li=new QListWidgetItem(ui->listWidget);
            li->setSizeHint(QSize(358,70+wordrow*25));
            ui->listWidget->setItemWidget(li,os);
        }
        io++;
    }
    ui->listWidget->scrollToBottom();
}

